package com.example.dangdangbackend.service.impl;

import com.example.dangdangbackend.DTO.AddOrderDTO;
import com.example.dangdangbackend.VO.BookTableVO;
import com.example.dangdangbackend.VO.OrderAndItemVO;
import com.example.dangdangbackend.VO.OrderDetailVO;
import com.example.dangdangbackend.common.BaseContext;
import com.example.dangdangbackend.entity.Order;
import com.example.dangdangbackend.mapper.OrderMapper;
import com.example.dangdangbackend.service.OrderService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public Order addOrder(AddOrderDTO addOrderDTO) {
        int userId = BaseContext.getCurrentId();
        Order o = new Order();
        o.setUserId(userId);
        o.setStatus(1);
        o.setAddressId(addOrderDTO.getAddressId());
        o.setTotal(addOrderDTO.getTotal().doubleValue());

        String currentTimeString = LocalDateTime.now().format(formatter);
        LocalDateTime time = LocalDateTime.parse(currentTimeString, formatter);
        o.setCreateTime(time);

        orderMapper.insertIntoOrder(o);

        return o;
    }

    @Override
    public PageInfo<OrderDetailVO> getOrderDetail(int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderDetailVO> list = orderMapper.selectOrderDetail();

        PageInfo<OrderDetailVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public OrderAndItemVO findOrderAndItemsByOrderId(int orderId) {
        return orderMapper.findOrderAndItemsByOrderId(orderId);
    }

    @Override
    public Order getOrderByOrderId(int orderId) {
        return orderMapper.getOrderByOrderId(orderId);
    }
}
